package com.fcy.teamwork.repo

import com.fcy.teamwork.security.NoneFilterHostNameVerifier
import com.fcy.teamwork.security.initSSL
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {
    var token = ""
    private const val TIME_OUT = 10
    val gson: Gson = GsonBuilder()
        .setDateFormat("yyyy-MM-dd HH:mm:ss")
        .create()


    //    const val BASE_URL = "https://www.hahah.com:10086"
    const val BASE_URL = "https://192.168.43.234:10086"


    val okClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .initSSL()
            .cache(null)
            .hostnameVerifier(NoneFilterHostNameVerifier())
            .addInterceptor { chain: Interceptor.Chain ->
                val tokenTmp = token
                val request = if (tokenTmp.isNotBlank()) {
                    chain.request().newBuilder().header("token", tokenTmp).build()
                } else chain.request()
                chain.proceed(request)
            }
            .addNetworkInterceptor(HttpLoggingInterceptor().apply {
                setLevel(HttpLoggingInterceptor.Level.BODY)
            })
            .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .build()
    }

    inline fun <reified T> getService(baseUrl: String = BASE_URL): T = Retrofit.Builder()
        .client(okClient)
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
        .create(T::class.java)
}